package com.ruoyi.system.auto;

import com.ruoyi.system.domain.GwContract;
import com.ruoyi.system.schedule.ScheduledTaskService;
import com.ruoyi.system.schedule.TimingTask;
import com.ruoyi.system.service.IGwContractService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 项目启动后 自动加载定时任务
 * </p>
 *
 * @author ShuaiYoung
 * @since 2025-7-1
 */
@Component
public class AutoStart implements CommandLineRunner {

    @Resource
    ScheduledTaskService scheduledTaskService;
    @Resource
    IGwContractService gwContractService;

    @Override
    public void run(String... args) {
        try {
            List<TimingTask> startTasks = new ArrayList<>();

            GwContract gwContract = new GwContract();
            gwContract.setStatus("PREPARE");
            for (GwContract contract : gwContractService.selectGwContractAllList(gwContract)) {
                //执行任务时间
                Instant instantPush = contract.getCreateTime().toInstant();
                ZoneId zoneId = ZoneId.systemDefault();
                ZonedDateTime zonedDateTime = instantPush.atZone(zoneId);
                LocalDateTime pushTime = zonedDateTime.toLocalDateTime().plusMinutes(31);
                // 转换为Date
                Instant instant = pushTime.atZone(ZoneId.systemDefault()).toInstant();
                //当前时间
                LocalDateTime now = LocalDateTime.now();
                if (now.compareTo(pushTime) >= 0) {
                    //超时删除
                    GwContract query = gwContractService.selectGwContractById(contract.getId() + "");
                    if (ObjectUtils.isNotEmpty(query) && "PREPARE".equals(query.getStatus())) {
                        gwContractService.deleteGwContractById(query.getId() + "");
                    }
                } else {
                    //设置定时执行任务
                    TimingTask taskVo = new TimingTask();
                    //执行任务时间
                    Date date = Date.from(instant);
                    taskVo.setStartDate(date);
                    taskVo.setTempFlag(true);
                    taskVo.setOrderId(contract.getId() + "");
                    startTasks.add(taskVo);
                }
            }
            if (ObjectUtils.isNotEmpty(startTasks)) {
                scheduledTaskService.startTask(startTasks);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}